﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Thread_Second
{
    public partial class Form1 : Form
    {
        private Thread th;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //判断线程是否正在运行，如果是小邋遢
            if (th != null)
                th.Abort();

            //创建线程去调用计时方法
            th = new Thread(Second);

            //创建线程去调用方法
            th.IsBackground = true;

            //开始线程
            th.Start();
        }
        private void Second()
        {
            for (int i = 0; i < 10000; i++)
            {
                Thread.Sleep(1000);
                textBox1.Text = i.ToString();
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //取消跨线程错误检测
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //当关闭窗体时，把后台线程也杀了
            if (th != null)
                th.Abort();
        }
    }
}
